// Dify API 配置
const DIFY_BASE_URL = 'http://192.168.0.170/v1';
const DIFY_API_KEY = 'app-us3IVdDty5Xgw0O6Geft4qdu';

/**
 * 格式化错误消息，提取友好的错误提示
 */
function formatErrorMessage(errorMsg: string): string {
  if (!errorMsg) return '发生未知错误，请稍后重试';
  
  // 连接错误
  if (errorMsg.includes('ConnectionError') || errorMsg.includes('Failed to resolve') || errorMsg.includes('No address associated')) {
    if (errorMsg.includes('dashscope.aliyuncs.com')) {
      return '无法连接到阿里云服务，请检查网络连接或联系管理员';
    }
    return '网络连接失败，请检查网络连接后重试';
  }
  
  // 超时错误
  if (errorMsg.includes('timeout') || errorMsg.includes('Timeout')) {
    return '请求超时，请稍后重试';
  }
  
  // 认证错误
  if (errorMsg.includes('401') || errorMsg.includes('Unauthorized') || errorMsg.includes('authentication')) {
    return '认证失败，请检查 API 密钥配置';
  }
  
  // 权限错误
  if (errorMsg.includes('403') || errorMsg.includes('Forbidden')) {
    return '没有权限访问该资源';
  }
  
  // 服务错误
  if (errorMsg.includes('500') || errorMsg.includes('Internal Server Error')) {
    return '服务器内部错误，请稍后重试';
  }
  
  // 服务不可用
  if (errorMsg.includes('503') || errorMsg.includes('Service Unavailable')) {
    return '服务暂时不可用，请稍后重试';
  }
  
  // 速率限制
  if (errorMsg.includes('429') || errorMsg.includes('rate limit') || errorMsg.includes('RateLimit')) {
    return '请求过于频繁，请稍后再试';
  }
  
  // 模型相关错误
  if (errorMsg.includes('model') || errorMsg.includes('Model')) {
    return '模型服务异常，请稍后重试';
  }
  
  // 提取关键错误信息（尝试提取中文错误信息）
  const chineseMatch = errorMsg.match(/[\u4e00-\u9fa5]+[^，。！？]*[，。！？]?/);
  if (chineseMatch) {
    return chineseMatch[0].trim();
  }
  
  // 提取错误代码
  const codeMatch = errorMsg.match(/code[":\s]+"?([^",}\s]+)"?/i);
  if (codeMatch) {
    return `错误代码: ${codeMatch[1]}`;
  }
  
  // 如果错误消息太长，截取前200个字符
  if (errorMsg.length > 200) {
    return errorMsg.substring(0, 200) + '...';
  }
  
  return errorMsg;
}

// 测试页面对话接口（直接调用Dify API）
export async function testChat(params: {
  query: string;
  conversation_id?: string;
  user?: string;
  onMessage?: (message: string) => void;
  onError?: (error: Error) => void;
  onComplete?: () => void;
}) {
  const { query, conversation_id, user, onMessage, onError, onComplete } = params;
  
  try {
    const requestBody = {
      inputs: {},
      query,
      response_mode: 'streaming',
      conversation_id: conversation_id || undefined,
      user: user || 'user',
    };

    console.log('Dify API请求:', {
      url: `${DIFY_BASE_URL}/chat-messages`,
      body: requestBody,
    });

    const response = await fetch(`${DIFY_BASE_URL}/chat-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DIFY_API_KEY}`,
      },
      body: JSON.stringify(requestBody),
    });

    console.log('Dify API响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Dify API错误响应:', errorText);
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('Response body is not readable');
    }

    const decoder = new TextDecoder();
    let buffer = '';
    let fullResponse = '';
    let conversationId = conversation_id;
    let hasReceivedData = false;
    // 跟踪所有收到的完整内容，选择最长的作为最终答案
    let maxLengthResponse = '';

    console.log('开始读取流式响应...');

    let streamError = false;
    let shouldBreak = false;
    while (true) {
      if (shouldBreak) {
        break;
      }
      
      const { done, value } = await reader.read();
      
      if (done) {
        console.log('流式响应读取完成');
        if (!streamError) {
          onComplete?.();
        }
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (shouldBreak) {
          break;
        }
        
        if (!line.trim()) continue;
        
        console.log('收到SSE行:', line);
        
        if (line.startsWith('data: ')) {
          const data = line.slice(6).trim();
          if (data === '[DONE]' || data === '') {
            continue;
          }
          
          try {
            const json = JSON.parse(data);
            console.log('解析的JSON数据:', json);
            
            if (json.event) {
              if (json.event === 'message' || json.event === 'message_chunk' || json.event === 'message_file' || json.event === 'agent_message') {
                const answerText = json.answer || json.text || json.content || '';
                // 注意：agent_message 事件可能返回空字符串，但这是正常的（表示当前没有新内容）
                // 只有当 answerText 非空时才处理
                if (answerText) {
                  if (json.event === 'message_chunk') {
                    // message_chunk 是增量内容，直接追加
                    fullResponse += answerText;
                    hasReceivedData = true;
                    console.log('收到chunk增量，当前总长度:', fullResponse.length, '本次增量:', answerText.substring(0, 50));
                  } else {
                    // agent_message 和 message 事件：answer 是累积内容
                    // 如果新内容更长或相等，说明是累积更新（使用更长的内容）
                    if (answerText.length >= fullResponse.length) {
                      fullResponse = answerText;
                      hasReceivedData = true;
                      // 更新最长内容
                      if (answerText.length > maxLengthResponse.length) {
                        maxLengthResponse = answerText;
                      }
                      console.log('收到message累积更新，总长度:', fullResponse.length, '内容预览:', answerText.substring(0, 50));
                    } else if (!fullResponse) {
                      // 如果还没有内容，直接使用
                      fullResponse = answerText;
                      hasReceivedData = true;
                      maxLengthResponse = answerText;
                      console.log('收到message初始内容，总长度:', fullResponse.length);
                    }
                    // 注意：如果新内容更短且已有内容，可能是部分更新，但通常 agent_message 的 answer 是累积的，所以不处理更短的情况
                  }
                  
                  if (hasReceivedData) {
                    onMessage?.(fullResponse);
                  }
                } else {
                  // answerText 为空，但这是正常的（可能是中间状态），不处理
                  console.log('收到空的answer，跳过处理');
                }
                
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                  console.log('获取到会话ID:', conversationId);
                }
              } else if (json.event === 'agent_thought') {
                // agent_thought 事件包含完整的思考内容，通常包含完整答案
                // 从日志看，thought 字段包含完整内容："您是想做哪项业务？可选：\n年度需求预测\n..."
                const thoughtText = json.thought || json.answer || json.text || json.content || '';
                if (thoughtText) {
                  // agent_thought 的 thought 字段通常包含完整答案，优先使用（如果更长或内容更完整）
                  // 注意：thought 字段可能包含完整的答案，即使长度相同也应该使用（因为内容可能更完整）
                  if (thoughtText.length >= fullResponse.length) {
                    // 如果 thought 更长或相等，使用 thought（通常更完整）
                    if (thoughtText.length > fullResponse.length || thoughtText !== fullResponse) {
                      fullResponse = thoughtText;
                      hasReceivedData = true;
                      // 更新最长内容
                      if (thoughtText.length > maxLengthResponse.length) {
                        maxLengthResponse = thoughtText;
                      }
                      console.log('收到agent_thought完整内容，总长度:', fullResponse.length, '内容预览:', thoughtText.substring(0, 100));
                      onMessage?.(fullResponse);
                    }
                  } else if (thoughtText.length > maxLengthResponse.length) {
                    // 即使 thought 比当前 fullResponse 短，但如果比 maxLengthResponse 长，也更新
                    maxLengthResponse = thoughtText;
                    console.log('agent_thought内容比当前长，更新maxLengthResponse，长度:', thoughtText.length);
                  }
                }
                
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                  console.log('获取到会话ID:', conversationId);
                }
              } else if (json.event === 'message_end') {
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                  console.log('消息结束，会话ID:', conversationId);
                }
                // message_end 事件可能包含完整的答案
                const endAnswerText = json.answer || json.text || json.content || '';
                if (endAnswerText && endAnswerText.length > fullResponse.length) {
                  fullResponse = endAnswerText;
                  hasReceivedData = true;
                  console.log('message_end事件包含完整答案，总长度:', fullResponse.length);
                }
                // 确保最终消息被发送
                if (fullResponse) {
                  onMessage?.(fullResponse);
                }
                onComplete?.();
              } else if (json.event === 'error') {
                const errorMsg = json.message || json.error || 'Unknown error';
                console.error('Dify返回错误:', errorMsg);
                // 保存会话ID（如果有）
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                }
                // 优化错误消息显示
                const friendlyErrorMsg = formatErrorMessage(errorMsg);
                // 调用错误回调并停止读取
                streamError = true;
                shouldBreak = true;
                const error = new Error(friendlyErrorMsg);
                // 保存原始错误消息到 error 对象
                (error as any).originalMessage = errorMsg;
                onError?.(error);
                // 停止读取流
                try {
                  reader.cancel();
                } catch (e) {
                  console.warn('取消流读取失败:', e);
                }
                break;
              }
            } else {
              if (json.answer || json.text || json.content) {
                const answerText = json.answer || json.text || json.content;
                if (fullResponse && answerText.length > fullResponse.length) {
                  const newPart = answerText.substring(fullResponse.length);
                  if (newPart) {
                    fullResponse += newPart;
                  } else {
                    fullResponse = answerText;
                  }
                } else if (!fullResponse) {
                  fullResponse = answerText;
                } else {
                  fullResponse += answerText;
                }
                hasReceivedData = true;
                console.log('直接更新回答内容（无event），当前长度:', fullResponse.length);
                onMessage?.(fullResponse);
              }
              
              if (json.conversation_id && !conversationId) {
                conversationId = json.conversation_id;
              }
            }
          } catch (e) {
            console.warn('解析SSE数据失败:', data, e);
            if (data && !data.startsWith('{')) {
              fullResponse += data;
              hasReceivedData = true;
              onMessage?.(fullResponse);
            }
          }
        } else if (line.startsWith('event: ')) {
          const eventType = line.slice(7).trim();
          console.log('收到事件类型:', eventType);
        }
      }
    }

    // 如果发生错误，直接返回，不处理后续数据
    if (streamError) {
      return {
        conversation_id: conversationId || conversation_id || undefined,
        answer: '',
      };
    }

    // 流结束时，使用最长的内容作为最终答案
    if (maxLengthResponse && maxLengthResponse.length > fullResponse.length) {
      console.log('使用maxLengthResponse作为最终答案，长度:', maxLengthResponse.length, '原长度:', fullResponse.length);
      fullResponse = maxLengthResponse;
      hasReceivedData = true;
      onMessage?.(fullResponse);
    }
    
    // 流结束时，确保最后一次更新消息（如果还没有通过 message_end 更新）
    if (fullResponse && hasReceivedData) {
      console.log('流结束，最终消息长度:', fullResponse.length, '内容预览:', fullResponse.substring(0, 100));
      onMessage?.(fullResponse);
    }

    if (!hasReceivedData && !fullResponse) {
      console.warn('未收到任何数据，可能是响应格式不匹配');
    }
    
    // 如果最终内容太短，可能是没有正确累积，记录警告
    if (fullResponse && fullResponse.length < 10) {
      console.warn('最终消息内容可能不完整，长度:', fullResponse.length, '内容:', fullResponse);
    }

    if (buffer.trim()) {
      console.log('处理剩余的缓冲区数据:', buffer);
      if (buffer.startsWith('data: ')) {
        const data = buffer.slice(6).trim();
        if (data !== '[DONE]' && data) {
          try {
            const json = JSON.parse(data);
            console.log('解析剩余数据的JSON:', json);
            // 检查是否是错误
            if (json.event === 'error') {
              const errorMsg = json.message || json.error || 'Unknown error';
              const friendlyErrorMsg = formatErrorMessage(errorMsg);
              const error = new Error(friendlyErrorMsg);
              (error as any).originalMessage = errorMsg;
              onError?.(error);
              return {
                conversation_id: conversationId || conversation_id || undefined,
                answer: '',
              };
            }
            if (json.answer || json.text || json.content) {
              const answerText: string = json.answer || json.text || json.content;
              fullResponse += answerText;
              hasReceivedData = true;
              onMessage?.(fullResponse);
            }
            if (json.conversation_id && !conversationId) {
              conversationId = json.conversation_id;
            }
          } catch (e) {
            console.warn('解析剩余数据失败:', e);
          }
        }
      }
    }

    console.log('最终返回数据:', {
      conversation_id: conversationId || conversation_id || undefined,
      answerLength: fullResponse.length,
      hasReceivedData,
    });

    return {
      conversation_id: conversationId || conversation_id || undefined,
      answer: fullResponse,
    };
  } catch (error) {
    const err = error instanceof Error ? error : new Error('Unknown error');
    onError?.(err);
    throw err;
  }
}

